package com.example.caorl.job1to4.backserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class BackendServer01 {

    // 后台服务端口
    public static final int BACKEND_PORT = 8081;
    // 运行标志位
    public static final AtomicBoolean RunningFlag = new AtomicBoolean(true);

    private static Logger logger = LoggerFactory.getLogger(BackendServer01.class);

    public static void main(String[] args) {
        try {
            final ServerSocket serverSocket = new ServerSocket(BACKEND_PORT);
            logger.info("开启后端服务器，监听端口：{}", BACKEND_PORT);
//            System.out.println("availableProcessors--------------"+Runtime.getRuntime().availableProcessors());
            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);
            /*ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                    1,1,10, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(1),
                    new ThreadPoolExecutor.DiscardOldestPolicy());*/

            while (RunningFlag.get()) {
                Socket accept = serverSocket.accept();
                executorService.execute(() -> {
                    service(accept);
                });
            }
            // 循环退出之后关闭服务
            serverSocket.close();
            executorService.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void service(Socket socket){
       try {
           logger.info("{}端口收到请求:-------------", BACKEND_PORT);
           InputStream inputStream = socket.getInputStream();

           PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
           printWriter.println("HTTP/1.0 200 OK");
           printWriter.println("Content-Type:text/html;charset=UTF-8");
           String body = "<h1>result from " + BACKEND_PORT +"</h1>";
           printWriter.println("Content-Length:"+body.getBytes().length);
           printWriter.println(); //这个不能删除，区分响应报头与响应正文
           printWriter.write(body);
           printWriter.close();
           socket.close(); //这个关闭后才返回结果
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}
